<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="502"
    :height="900"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{ maxWidth: '750px' }"
      >
        <n-form-item
          label="类型"
          path="type"
        >
          <n-select
            v-model:value="formValue.type"
            :options="TaskLogData.getTypeOptions()"
            @update:value="formValue.taskId = undefined"
          />
        </n-form-item>
        <n-form-item
          label="任务"
          path="taskId"
        >
          <!--          {{ choose }}-->
          <template v-if="formValue.type === 1">
            <n-select
              v-model:value="choose.chooseField"
              @update:value="
                choose.chooseStage = undefined;
                formValue.taskId = undefined;
              "
              :options="fieldTree.getFieldSelectOptions()"
              filterable
            />
            <n-select
              v-model:value="choose.chooseStage"
              @update:value="formValue.taskId = undefined"
              :options="stageOptions"
              filterable
            />
            <n-select
              v-model:value="formValue.taskId"
              :options="taskOptions"
              filterable
            />
          </template>
          <template v-if="formValue.type === 2">
            <n-select
              v-model:value="choose.chooseLifeModel"
              @update:value="formValue.taskId = undefined"
              :options="lifeModel.getLifeModelSelectOptions()"
            />
            <n-select
              v-model:value="formValue.taskId"
              :options="
                timeManageList.getTimeManageSelectOptions(lifeModel.getLifeModelDataById(choose.chooseLifeModel))
              "
            />
          </template>
        </n-form-item>
        <n-form-item
          label="开始时间"
          path="startTime"
        >
          <n-date-picker
            type="datetime"
            v-model:value="formValue.startTime"
          />
        </n-form-item>
        <n-form-item
          label="结束时间"
          path="endTime"
        >
          <n-date-picker
            type="datetime"
            v-model:value="formValue.endTime"
          />
        </n-form-item>
        <n-form-item
          label="留言"
          path="markDownFile"
        >
          <n-input
            v-model:value="formValue.markDownFile"
            type="textarea"
            placeholder="感想"
          />
        </n-form-item>
        <n-form-item
          label="是否加入回忆"
          path="isMemory"
        >
          <n-switch v-model:value="formValue.isMemory">
            <template #unchecked>回忆</template>
          </n-switch>
        </n-form-item>
        <n-form-item
          label="图片"
          path="picList"
        >
          <PicShowList v-model="picShowListModel"></PicShowList>
        </n-form-item>
        <n-form-item
          label="视频"
          path="mediaList"
        >
          <VedioShowList v-model="vedioShowListModel"></VedioShowList>
        </n-form-item>
        <n-form-item
          label="地址"
          path="location"
        >
          <!--            <n-time-picker v-model:value="formValue.location" />-->
          <n-button @click="Location.getLocation()">获取地址</n-button>
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script
  lang="ts"
  setup
  generic="T extends object &
{ toEdit: boolean,toDelete:boolean,toDealRowId: string|undefined,toRecord:boolean}"
>
import PicShowList from "@/components/common/PicShowList.vue";
import VedioShowList from "@/components/common/VedioShowList.vue";
import { TaskLogData } from "@model/TaskLogMap";
import { Location } from "@model/TaskLogMap";
import { StageList } from "@model/stage";
import { TimeManageList } from "@model/timeManage";
import UseCacheIdStatMap from "@pinias/UseCacheIdStatMap";
import UseCacheMemory from "@pinias/UseCacheMemory";
import UseCacheTaskLog from "@pinias/UseCacheTaskLog";
import UseFieldTree from "@pinias/UseFieldTree";
import UseLifeModel from "@pinias/UseLifeModel";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import UseTask from "@pinias/UseTask";
import UseTimeManageList from "@pinias/UseTimeManageList";
import pinia from "@pinias/pinia";
import { DateTimeStr } from "@utils/DateUtils";
import { FormInst, NButton, NDrawer, NDrawerContent, NForm, NFormItem, NInput, useMessage } from "naive-ui";
import { computed, reactive, ref, watch } from "vue";
import { onMounted } from "vue";

// 全局数据
const { getCacheTaskLogMap } = UseCacheTaskLog(pinia);
const cacheTaskLogMap = getCacheTaskLogMap();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();
const { getTaskList } = UseTask(pinia);
const taskList = getTaskList();
const { getLifeModel } = UseLifeModel(pinia);
const lifeModel = getLifeModel();
const { getTimeManageList } = UseTimeManageList(pinia);
const timeManageList: TimeManageList = getTimeManageList();
const { getCacheIdStatMap } = UseCacheIdStatMap(pinia);
const cacheIdStatMap = getCacheIdStatMap();
const { getCacheMemory } = UseCacheMemory(pinia);
const cacheMemory = getCacheMemory();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting = getSurfaceSetting();
// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});
// 页面数据
// 选项
const choose = reactive<{
  chooseField: number | undefined;
  chooseStage: number | undefined;
  chooseLifeModel: number | undefined;
}>({
  chooseField: undefined,
  chooseStage: undefined,
  chooseLifeModel: undefined,
});
const taskOptions = ref<Array<{ label: string; value: number }>>([]);
const stageOptions = ref<Array<{ label: string; value: number }>>([]);
watch(choose, async () => {
  if (choose.chooseStage !== undefined)
    taskOptions.value = await cacheTaskLogMap.getTaskSelectOptions2(
      stageList.getStageDataById(choose.chooseStage),
      true,
      taskList,
    );
  if (choose.chooseField !== undefined)
    stageOptions.value = await cacheTaskLogMap.getStageSelectOptions2(
      fieldTree.getFieldDataById(choose.chooseField),
      true,
      stageList,
    );
});
// 表单数据
const formRef = ref<FormInst | null>(null);
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  type: {
    type: "number",
    required: true,
    message: "请选择类型",
    trigger: ["blur", "change"],
  },
  taskId: {
    type: "number",
    required: true,
    message: "请选择任务",
    trigger: ["blur", "change"],
  },
  startTime: {
    type: "number",
    required: true,
    message: "请输入開始时间",
    trigger: ["blur", "change"],
  },
  endTime: {
    type: "number",
    required: true,
    message: "请输入结束时间",
    trigger: ["blur", "change"],
  },
};
const getNewFormValue = async () => {
  // console.log('getNewFormValue',toDealItem);
  const nullModel = TaskLogData.getNullModel();
  nullModel.taskId = undefined;
  if (toADDFlag.value) {
    // 结束计时的情况
    if (modelValue.value.toRecord) {
      const endTime = new Date().getTime();
      const dateTimeStr = new DateTimeStr(endTime);
      const taskBoardList = surfaceSetting.taskBoardList;
      const taskLogData = new TaskLogData(
        dateTimeStr.getTimeInfo(),
        taskBoardList.recordType,
        taskBoardList.recordTaskId,
        taskBoardList.recordBeginTime,
        endTime,
        new Location(),
        false,
      );
      return taskLogData;
    }
  } else {
    if (modelValue.value.toDealRowId !== undefined) {
      const timeStamp = DateTimeStr.getTimeStamp(modelValue.value.toDealRowId);
      const taskLogMap = await cacheTaskLogMap.getTaskLogMap(timeStamp);
      const taskLogData = taskLogMap.taskLogMap.get(modelValue.value.toDealRowId);
      if (taskLogData !== undefined) {
        // const copy = TaskLogData.copyLogData(taskLogData);
        // return await TaskLogData.getFullMediaPath(copy);
        return TaskLogData.copyLogData(taskLogData);
      }
    }
  }
  return nullModel;
};
const formValue = ref<TaskLogData>(TaskLogData.getNullModel());
const oldValue = ref<TaskLogData>(TaskLogData.getNullModel());
const watchFormValue = async () => {
  // editSettings.state = taskState.value;
  // console.log(formValue);
  formValue.value = await getNewFormValue();
  oldValue.value = await getNewFormValue();
  if (formValue.value.taskId !== undefined && formValue.value.taskId > 0) {
    const newFatherId = await TaskLogData.getFatherId(formValue.value.type, formValue.value.taskId);
    if (formValue.value.type == 1 && newFatherId != undefined && newFatherId.length > 2) {
      choose.chooseField = newFatherId[2].id;
      choose.chooseStage = newFatherId[1].id;
    }
    if (formValue.value.type == 2 && newFatherId != undefined && newFatherId.length > 1) {
      choose.chooseLifeModel = newFatherId[1].id;
    }
  } else {
    choose.chooseField = undefined;
    choose.chooseStage = undefined;
    choose.chooseLifeModel = undefined;
  }
  picShowListModel.picList = formValue.value.picList;
  vedioShowListModel.picList = formValue.value.mediaList;
  // console.log(picShowListModel.picList,formValue.value.picList,"++++++++++++++++++++++++")
};
onMounted(async () => {
  await watchFormValue();
});
watch(modelValue.value, watchFormValue);

// 图片文件处理
const picShowListModel = reactive({
  toRemovePicList: new Array<string>(),
  picList: formValue.value.picList,
  toEdit: true,
});
const vedioShowListModel = reactive({
  toRemovePicList: new Array<string>(),
  picList: formValue.value.picList,
  toEdit: true,
});

// 提交逻辑
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      // message.success("Valid");
      await addNewOne();
      surfaceSetting.memoryPanelKey = new Date().getTime();
    } else {
      console.log(errors);
      // message.error("Invalid");
    }
  });
};
const message = useMessage();
const addNewOne = async () => {
  const tosave = formValue.value;
  let taskdLogData = undefined;
  let id = tosave.id;
  if (toADDFlag.value) {
    // 根据开始时间生成id
    const dateTimeStr = new DateTimeStr(tosave.startTime);
    id = dateTimeStr.getTimeInfo();
  }
  // 生成TaskLogData对象
  taskdLogData = new TaskLogData(
    id,
    tosave.type,
    tosave.taskId,
    tosave.startTime,
    tosave.endTime,
    tosave.location,
    tosave.isMemory,
  );
  //跟换media信息
  taskdLogData.markDownFile = tosave.markDownFile;
  taskdLogData.mediaList = tosave.mediaList;
  taskdLogData.picList = tosave.picList;
  // let list = TaskLogData.removePath(oldValue.value.mediaList,tosave.mediaList)
  // surfaceSetting.toRemoveMediaPath.push(...list)
  // console.log("surfaceSetting.toRemoveMediaPath",oldValue.value.picList,tosave.picList)
  // list = TaskLogData.removePath(oldValue.value.picList,tosave.picList)
  // surfaceSetting.toRemoveMediaPath.push(...list)
  surfaceSetting.toRemoveMediaPath = [...picShowListModel.toRemovePicList, ...vedioShowListModel.toRemovePicList];
  // console.log("surfaceSetting.toRemoveMediaPath", surfaceSetting.toRemoveMediaPath, toRemovePicList);
  picShowListModel.toRemovePicList = [];
  vedioShowListModel.toRemovePicList = [];
  // taskdLogData = await TaskLogData.getBaseMediaPath(taskdLogData);

  const tosaveList = new Array<TaskLogData>();
  tosaveList.push(taskdLogData);
  // 加入对象中
  const string = await cacheTaskLogMap.addTaskLogData(tosaveList);
  if (string.length > 0) message.error(string);
  else {
    // 统计情况：找到taskId，加入其中；然后找到父id，加入其中
    const oldFatherId = await TaskLogData.getFatherId(oldValue.value.type, oldValue.value.taskId);
    const newFatherId = await TaskLogData.getFatherId(tosave.type, tosave.taskId);
    if (
      toADDFlag.value ||
      oldValue.value.taskId !== tosave.taskId ||
      oldValue.value.startTime !== tosave.startTime ||
      oldValue.value.endTime !== tosave.endTime ||
      oldValue.value.isMemory !== tosave.isMemory
    ) {
      // 删除原来的;添加新的
      await cacheIdStatMap.changeTaskLogData4Stat(
        [oldValue.value],
        oldFatherId.map(value => value.id),
        tosaveList,
        newFatherId.map(value => value.id),
      );
    }
    // 回忆情况：按照顺序加入回忆
    if (oldValue.value.isMemory !== tosave.isMemory) {
      if (tosave.isMemory) await cacheMemory.addMemory(tosaveList);
      else await cacheMemory.deleteMemory(tosaveList);
    }
    modelValue.value.toEdit = false;
  }
  surfaceSetting.memoryPanelKey = new Date().getTime();
};
</script>
